<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆管理系统 - 系统配置</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="auth.js"></script>
    <script src="permission-control.js"></script>
</head>
<body>
    <!-- 主系统页面 -->
    <div id="mainPage" class="page active">
        <!-- 顶部导航栏 -->
        <header class="header">
            <div class="header-left">
                <button class="sidebar-toggle" onclick="toggleSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <h1 class="logo">
                    <i class="fas fa-book"></i>
                    图书馆管理系统
                </h1>
            </div>
            <div class="header-right">
                <div class="notification-icon" onclick="showNotifications()">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge" id="notificationBadge">0</span>
                </div>
                <div class="user-menu">
                    <span class="user-name" id="currentUserName">管理员</span>
                    <div class="user-dropdown">
                        <button class="dropdown-btn">
                            <i class="fas fa-user-circle"></i>
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <div class="dropdown-content">
                            <a href="#" onclick="showProfile()">个人资料</a>
                            <a href="#" onclick="changePassword()">修改密码</a>
                            <a href="#" onclick="logout()">退出登录</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 侧边栏 -->
        <aside class="sidebar" id="sidebar">
            <nav class="sidebar-nav">
                <ul id="sidebarMenu">
                    <!-- 菜单将通过JavaScript动态生成 -->
                </ul>
            </nav>
        </aside>

        <!-- 主内容区域 -->
        <main class="main-content">
            <!-- 系统配置页面 -->
            <div id="system" class="content-page active">
                <div class="page-header">
                    <h2>系统配置</h2>
                    <p>管理系统的基本配置信息和运行参数</p>
                </div>

                <!-- 维护模式横幅 -->
                <div id="maintenanceBanner" class="alert alert-warning" style="display: none;">
                    <i class="fas fa-exclamation-triangle"></i>
                    系统当前处于维护模式
                </div>

                <div class="config-container">
                    <!-- 配置表单 -->
                    <form id="configForm">
                        <!-- 系统基础信息 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-info-circle"></i> 系统基础信息</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="system_name">系统名称</label>
                                            <input type="text" class="form-control" id="system_name" name="system_name" placeholder="请输入系统名称">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="library_name">图书馆名称</label>
                                            <input type="text" class="form-control" id="library_name" name="library_name" placeholder="请输入图书馆名称">
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="system_version">系统版本</label>
                                            <input type="text" class="form-control" id="system_version" name="system_version" placeholder="请输入系统版本">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="copyright_info">版权信息</label>
                                            <input type="text" class="form-control" id="copyright_info" name="copyright_info" placeholder="请输入版权信息">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 系统运行参数 -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-cogs"></i> 系统运行参数</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="password_min_length">密码最小长度</label>
                                            <input type="number" class="form-control" id="password_min_length" name="password_min_length" 
                                                   min="1" max="100" placeholder="请输入密码最小长度" onchange="validatePasswordLengths()">
                                            <small class="form-text text-muted">设置用户密码的最小长度要求</small>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="password_max_length">密码最大长度</label>
                                            <input type="number" class="form-control" id="password_max_length" name="password_max_length" 
                                                   min="1" max="100" placeholder="请输入密码最大长度" onchange="validatePasswordLengths()">
                                            <small class="form-text text-muted">设置用户密码的最大长度限制</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="form-group">
                                            <div class="form-check">
                                                <input type="checkbox" class="form-check-input" id="maintenance_mode" name="maintenance_mode">
                                                <label class="form-check-label" for="maintenance_mode">
                                                    系统维护模式
                                                </label>
                                            </div>
                                            <small class="form-text text-muted">开启后所有用户无法登录，需要密码关闭</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 操作按钮 -->
                        <div class="card">
                            <div class="card-body">
                                <div class="btn-group">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save"></i> 保存配置
                                    </button>
                                    <button type="button" class="btn btn-secondary" onclick="resetForm()">
                                        <i class="fas fa-undo"></i> 重置
                                    </button>
                                    <button type="button" class="btn btn-info" onclick="loadConfig()">
                                        <i class="fas fa-refresh"></i> 刷新
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <!-- 加载提示 -->
    <div id="loadingOverlay" class="loading-overlay">
        <div class="loading-spinner">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
        </div>
    </div>

    <!-- 消息提示 -->
    <div id="messageContainer" class="message-container">
    </div>

    <!-- 维护模式密码输入模态框 -->
    <div id="maintenanceModal" class="modal-overlay">
        <div class="modal">
            <div class="modal-header">
                <h3>关闭维护模式</h3>
                <button class="modal-close" onclick="closeMaintenanceModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <p>请输入管理员密码以关闭维护模式：</p>
                <input type="password" class="form-control" id="maintenancePassword" placeholder="请输入密码">
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="closeMaintenanceModal()">取消</button>
                <button class="btn btn-primary" onclick="confirmDisableMaintenance()">确认</button>
            </div>
        </div>
    </div>

    <script src="config.js"></script>
    <script>
        // API基础配置
        const API_BASE_URL = 'http://118.31.223.190:8080';

        // 通用API请求函数
        class ApiClient {
            constructor() {
                this.baseURL = API_BASE_URL;
            }

            async request(url, options = {}) {
                const isForm = options && options.body instanceof FormData;
                const headers = isForm ? (options.headers || {}) : { 'Content-Type': 'application/json', ...(options.headers || {}) };
                const config = { headers, ...options };

                try {
                    const response = await fetch(`${this.baseURL}${url}`, config);
                    const data = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    return data;
                } catch (error) {
                    console.error('API请求失败:', error);
                    throw error;
                }
            }

            async get(url, params = {}) {
                const queryString = new URLSearchParams(params).toString();
                const fullUrl = queryString ? `${url}?${queryString}` : url;
                return this.request(fullUrl, { method: 'GET' });
            }

            async post(url, data = {}) {
                if (data instanceof FormData) {
                    return this.request(url, { method: 'POST', body: data });
                }
                return this.request(url, { method: 'POST', body: JSON.stringify(data) });
            }

            async put(url, data = {}) {
                return this.request(url, {
                    method: 'PUT',
                    body: JSON.stringify(data)
                });
            }

            async delete(url) {
                return this.request(url, { method: 'DELETE' });
            }
        }

        // 创建API客户端实例
        const api = new ApiClient();

        // 系统配置API
        const SystemConfigAPI = {
            // 获取所有配置
            getAllConfigs: () => api.get('/api/system/config/all'),
            
            // 批量保存配置
            batchSaveConfigs: (configs) => api.post('/api/system/config/batch', configs),
            
            // 关闭维护模式
            disableMaintenanceMode: (password) => api.post('/api/system/config/maintenance/disable', { password })
        };

        // 工具函数
        const Utils = {
            // 显示加载状态
            showLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.add('active');
                }
            },

            // 隐藏加载状态
            hideLoading: () => {
                const loadingOverlay = document.getElementById('loadingOverlay');
                if (loadingOverlay) {
                    loadingOverlay.classList.remove('active');
                }
            },

            // 显示消息提示
            showMessage: (message, type = 'info', duration = 3000) => {
                const messageContainer = document.getElementById('messageContainer');
                if (!messageContainer) return;

                const messageEl = document.createElement('div');
                messageEl.className = `message ${type}`;
                
                const iconMap = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-exclamation-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle'
                };

                messageEl.innerHTML = `
                    <i class="${iconMap[type] || iconMap.info}"></i>
                    <span>${message}</span>
                    <button class="message-close" onclick="this.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                `;

                messageContainer.appendChild(messageEl);

                // 自动移除消息
                setTimeout(() => {
                    if (messageEl.parentElement) {
                        messageEl.remove();
                    }
                }, duration);
            }
        };

        // 系统配置管理器
        class SystemConfigManager {
            constructor() {
                this.configs = {};
                this.init();
            }

            async init() {
                await this.loadConfig();
                this.bindEvents();
                this.checkMaintenanceMode();
            }

            // 加载配置
            async loadConfig() {
                try {
                    Utils.showLoading();
                    const response = await SystemConfigAPI.getAllConfigs();
                    if (response.result === 'SUCCESS') {
                        const configs = response.data || [];
                        this.populateForm(configs);
                    }
                } catch (error) {
                    console.error('加载配置失败:', error);
                    Utils.showMessage('加载配置失败', 'error');
                } finally {
                    Utils.hideLoading();
                }
            }

            // 填充表单
            populateForm(configs) {
                configs.forEach(config => {
                    const element = document.getElementById(config.configKey);
                    if (element) {
                        if (element.type === 'checkbox') {
                            element.checked = config.configValue === 'true';
                        } else {
                            element.value = config.configValue;
                        }
                    }
                });
            }

            // 保存配置
            async saveConfig(formData) {
                try {
                    Utils.showLoading();
                    const response = await SystemConfigAPI.batchSaveConfigs(formData);

                    if (response.result === 'SUCCESS') {
                        Utils.showMessage('配置保存成功', 'success');
                        
                        // 检查是否开启了维护模式
                        if (formData.maintenance_mode === 'true') {
                            // 延迟跳转，让用户看到保存成功的消息
                            setTimeout(() => {
                                Utils.showMessage('系统维护模式已开启，即将跳转到维护页面...', 'warning', 2000);
                                setTimeout(() => {
                                    window.location.href = 'maintenance.html';
                                }, 2000);
                            }, 1000);
                        } else {
                            await this.loadConfig();
                        }
                    } else {
                        throw new Error('保存失败');
                    }
                } catch (error) {
                    console.error('保存配置失败:', error);
                    Utils.showMessage('保存配置失败', 'error');
                } finally {
                    Utils.hideLoading();
                }
            }

            // 绑定事件
            bindEvents() {
                const form = document.getElementById('configForm');
                form.addEventListener('submit', (e) => {
                    e.preventDefault();
                    
                    if (!this.validateForm()) {
                        return;
                    }

                    const formData = new FormData(form);
                    const configs = {};
                    
                    for (let [key, value] of formData.entries()) {
                        configs[key] = value;
                    }
                    
                    // 处理复选框
                    const maintenanceMode = document.getElementById('maintenance_mode');
                    configs['maintenance_mode'] = maintenanceMode.checked ? 'true' : 'false';
                    
                    this.saveConfig(configs);
                });

                // 维护模式切换事件
                document.getElementById('maintenance_mode').addEventListener('change', (e) => {
                    if (!e.target.checked) {
                        // 如果是关闭维护模式，显示密码输入框
                        document.getElementById('maintenanceModal').classList.add('active');
                        e.target.checked = true; // 先保持选中状态
                    }
                });
            }

            // 验证表单
            validateForm() {
                return validatePasswordLengths();
            }

            // 检查维护模式
            async checkMaintenanceMode() {
                if (window.globalConfig) {
                    await window.globalConfig.checkMaintenanceMode();
                }
            }
        }

        // 密码长度验证
        function validatePasswordLengths() {
            const minLength = parseInt(document.getElementById('password_min_length').value);
            const maxLength = parseInt(document.getElementById('password_max_length').value);
            
            const minInput = document.getElementById('password_min_length');
            const maxInput = document.getElementById('password_max_length');
            
            // 重置样式
            minInput.classList.remove('is-valid', 'is-invalid');
            maxInput.classList.remove('is-valid', 'is-invalid');
            
            if (minLength && maxLength) {
                if (minLength > maxLength) {
                    minInput.classList.add('is-invalid');
                    maxInput.classList.add('is-invalid');
                    Utils.showMessage('密码最小长度不能大于最大长度', 'error');
                    return false;
                } else {
                    minInput.classList.add('is-valid');
                    maxInput.classList.add('is-valid');
                }
            }
            
            return true;
        }

        // 重置表单
        function resetForm() {
            if (confirm('确定要重置所有配置吗？')) {
                document.getElementById('configForm').reset();
            }
        }

        // 刷新配置
        function loadConfig() {
            if (window.systemConfigManager) {
                window.systemConfigManager.loadConfig();
            }
        }

        // 关闭维护模式
        async function confirmDisableMaintenance() {
            const password = document.getElementById('maintenancePassword').value;
            
            if (!password) {
                Utils.showMessage('请输入密码', 'warning');
                return;
            }

            try {
                Utils.showLoading();
                const response = await SystemConfigAPI.disableMaintenanceMode(password);
                
                if (response.result === 'SUCCESS') {
                    Utils.showMessage('维护模式已关闭', 'success');
                    document.getElementById('maintenance_mode').checked = false;
                    closeMaintenanceModal();
                    // 重新加载配置以确保状态同步
                    setTimeout(() => {
                        window.systemConfigManager.loadConfig();
                    }, 1000);
                } else {
                    Utils.showMessage('密码错误', 'error');
                }
            } catch (error) {
                Utils.showMessage('操作失败', 'error');
            } finally {
                Utils.hideLoading();
            }
        }

        // 关闭维护模式模态框
        function closeMaintenanceModal() {
            document.getElementById('maintenanceModal').classList.remove('active');
            document.getElementById('maintenancePassword').value = '';
        }

        // 生成侧边栏菜单
        function generateSidebarMenu() {
            const sidebarMenu = document.getElementById('sidebarMenu');
            if (sidebarMenu) {
                sidebarMenu.innerHTML = authManager.generateSidebarMenu();
            }
        }

        // 侧边栏切换
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('active');
        }

        // 显示通知
        function showNotifications() {
            Utils.showMessage('通知功能开发中', 'info');
        }

        // 显示个人资料
        function showProfile() {
            Utils.showMessage('个人资料功能开发中', 'info');
        }

        // 修改密码
        function changePassword() {
            Utils.showMessage('修改密码功能开发中', 'info');
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                localStorage.removeItem('currentUser');
                window.location.href = 'login.html';
            }
        }

        // 全局变量
        let currentUser = null;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
        });

        // 初始化应用
        function initializeApp() {
            // 使用通用权限检查
            if (!initializePagePermission()) {
                return;
            }
            
            currentUser = authManager.getCurrentUser();
            
            // 生成动态菜单
            generateSidebarMenu();
            
            // 更新用户信息
            document.getElementById('currentUserName').textContent = currentUser.realName || currentUser.username;
            
            // 初始化系统配置管理器
            window.systemConfigManager = new SystemConfigManager();
        }

        // 检查登录状态
        function checkLoginStatus() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
            }
        }
    </script>
</body>
</html>